package com.apache.member.controller;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.util.Validator;
import com.apache.database.model.Page;
import com.apache.member.common.ConstantData;
import com.apache.member.common.DateUtil;
import com.apache.member.entity.Member;
import com.apache.member.manager.MemberManager;
import com.apache.member.manager.MemberRoleManager;
import com.apache.member.manager.MemberTypeManager;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.manager.UserManager;

@Controller
@RequestMapping("/web/member")
public class MemberWebController {

	@Autowired
	private MemberManager memberManager;

	@Autowired
	private MemberRoleManager memberRoleManager;

	@Autowired
	private MemberTypeManager memberTypeManager;

	@Autowired
	private UserManager userManager;;

	@RequestMapping("/getMember.action")
	@ResponseBody
	public Map<String, Object> selectById(Member member) {
		ParamsVo<Member> vo = new ParamsVo<Member>();
		vo.setObj(member);
		Map<String, Object> mapData = new HashMap<String, Object>();
		List<Member> list = memberManager.getList(vo);
		if (Validator.isEmpty(list)) {
			return null;
		}
		mapData.put("member", list.get(0));

		return mapData;
	}

	@RequestMapping("/selectById.action")
	@ResponseBody
	public Map<String, Object> selectById(String id) {
		ParamsVo<Member> vo = new ParamsVo<Member>();

		Map<String, Object> mapData = new HashMap<String, Object>();
		if (Validator.isNotNull(id)) {
			ParamsVo<Member> v = new ParamsVo<Member>();
			v.setInfoId(id);
			Member member = (Member) memberManager.getInfoById(v);
			mapData.put("member", member);
		}

		return mapData;
	}

	/**
	 * 添加
	 * @param member
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	//@Token(remove = true)
	//防表单重复提交注解
	@RequestMapping("add.action")
	@ResponseBody
	//定义注解
	public ResultMsg add(Member member, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ResultMsg resultMsg = new ResultMsg();
		resultMsg.setFlag(ConstantData.FLAG_FALSE);
		resultMsg.setMsg("操作失败！");

		ParamsVo vo = new ParamsVo();
		//默认注册的是普通会员会员等级1
		member.setMemberLevel(ConstantData.MemberLevel.NORMAL);
		String editType = request.getParameter("editType");//TODO
		if ("0".equals(editType)) {//TODO
			member.setAuditStatus(ConstantData.AuditStatus.TEMP);
		} else {
			member.setAuditStatus(ConstantData.AuditStatus.AUDIT_PASS);
		}
		member.setInfoFrom("1");//TODO
		member.setStatus("1");//TODO
		member.setCreateTime(DateUtil.getNowTime());
		member.setRegTime(DateUtil.getNowTime());
		String mobile = String.valueOf(Validator.getDefaultStr(member.getMobile(), null));
		if (Validator.isNotNull(mobile)) {
			member.setMobile(mobile);
		}
		vo.setObj(member);
		String memberId = memberManager.saveMemberAndUser(vo);//.saveMemberRoleInfo(vo);

		if (Validator.isNotNull(memberId)) {

			resultMsg.setFlag(ConstantData.FLAG_OK);
			resultMsg.setMsg(memberId);

		} else {

			resultMsg.setFlag(ConstantData.FLAG_FALSE);
			resultMsg.setMsg("账号已存在或网络异常，注册不成功！");
		}

		return resultMsg;
	}

	/**
	 * 会员认证申请
	 * @param member
	 * @param response
	 * @return
	 * @throws  
	 */
	//@Token(remove = true)
	//防表单重复提交注解
	@RequestMapping("auditApply.action")
	@ResponseBody
	//定义注解
	public ResultMsg auditApply(String auditType, String tableName, Member member, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ResultMsg resultMsg = new ResultMsg();
		resultMsg.setFlag(ConstantData.FLAG_FALSE);
		resultMsg.setMsg("提交审核失败");
		try {
			LoginUser loginUser = PBOSSOTools.getLoginUser(request);
			String memberId = member.getMemberId();
			if (Validator.isNotNull(memberId)) {
				// 删除会员的角色信息
				//				if (null != member.getMemberRoles() && !"".equals(member.getMemberRoles())) {
				//					//deleteMemberRole(member.getMemberId());
				//				}
				ParamsVo<Member> bmiVo = new ParamsVo<Member>();
				member.setUpdateTime(DateUtil.getNowTimeWithOutMinutes());
				member.setAuditStatus(ConstantData.AuditStatus.AUDITING);
				bmiVo.setObj(member);
				bmiVo.setParams("loginUser", loginUser);
				bmiVo.setParams("flag", "T");
				bmiVo.setParams("userEname", loginUser.getUserEname());
				bmiVo.setParams("pid", memberId);
				//修改会员的角色信息和基本信息，用最新的方法
				boolean bmiId = memberManager.editMemberInfoAndRole(bmiVo);
				//				boolean bmiId = memberManager.editMemberInfoAndRoleInOneMethod(bmiVo);
				if (bmiId) {
					resultMsg.setFlag(ConstantData.FLAG_OK);
					resultMsg.setMsg("提交审核成功!");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMsg;
	}

	/**
	 * 添加会员（此方法用于先有user后再添加member的场景）
	 * @param member
	 * @param response
	 * @return
	 */
	//@Token(remove = true)
	//防表单重复提交注解
	@RequestMapping("addMember.action")
	@ResponseBody
	//定义注解
	public ResultMsg addMember(Member member, HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ResultMsg resultMsg = new ResultMsg();
		resultMsg.setFlag(ConstantData.FLAG_FALSE);
		resultMsg.setMsg("操作失败！");
		ParamsVo<Member> vo = new ParamsVo<Member>();
		member.setAuditStatus(ConstantData.AuditStatus.AUDITING);
		member.setInfoFrom(ConstantData.InfoFrom.ONLINE);
		member.setStatus(ConstantData.UserStatus.START);

		String now = DateUtil.getNowTime();
		member.setCreateTime(now);
		member.setCreateUserEname(member.getMemberEname());
		member.setRegTime(now);
		String mobile = String.valueOf(Validator.getDefaultStr(member.getMobile(), null));
		if (Validator.isNotNull(mobile)) {
			member.setMobile(mobile);
		}
		vo.setObj(member);

		LoginUser loginUser = PBOSSOTools.getLoginUser(request);
		vo.setParams("loginUser", loginUser);
		vo.setParams("flag", "T");
		vo.setParams("userEname", loginUser.getUserEname());
		vo.setParams("pid", loginUser.getUserId());
		String auditType = request.getParameter("auditType");
		vo.setParams("auditType", Validator.getDefaultStr(auditType, null));
		String memberId = memberManager.saveMemberAndRoles(vo);
		if (Validator.isNotNull(memberId)) {
			resultMsg.setFlag(ConstantData.FLAG_OK);
			resultMsg.setMsg(memberId);
			String callBack = request.getParameter("callBack");
			if (Validator.isNotNull(callBack)) {
				JSONObject nvo = new JSONObject();
				PrintWriter out = response.getWriter();
				nvo.put("flag", ConstantData.FLAG_OK);
				response.getWriter().write(callBack + "(" + nvo.toString() + ")");
				return null;
			}

		} else {
			resultMsg.setFlag(ConstantData.FLAG_FALSE);
			resultMsg.setMsg("会员开通未成功！");
		}

		return resultMsg;
	}

	/**
	 * 专家列表
	 * description:  
	 * @param member
	 * @return  
	 * @author cbqiu 
	 * @update 2016-4-7
	 */
	@RequestMapping("/expertList.action")
	@ResponseBody
	public Map<String, Object> expertList(Member member, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ParamsVo<Member> vo = new ParamsVo<Member>();
		vo.setParams("roleEname", ConstantData.RoleEname.EXPERT);
		vo.setParams("shortName", member.getShortName());
		String pageSize = String.valueOf(request.getParameter("pageSize"));
		if (Validator.isNotNull(pageSize)) {
			vo.setParams("pageSize",pageSize);
		}
		Page pageList = memberManager.getExpertList(vo);

		String callBack = request.getParameter("callBack");
		if (Validator.isNotNull(callBack)) {
			JSONObject nvo = new JSONObject();
			PrintWriter out = response.getWriter();
			nvo.put("total", pageList.getCount());
			nvo.put("rows", pageList.getPageObjects());
			response.getWriter().write(callBack + "(" + nvo.toString() + ")");
			return null;
		}

		Map<String, Object> mapData = new HashMap<String, Object>();
		mapData.put("total", pageList.getCount());
		mapData.put("rows", pageList.getPageObjects());
		return mapData;
	}
}
